package com.lly.songhigh.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.adapter.AlbumDetialsDownloadAdapter;
import com.lly.songhigh.adapter.AlbumDetialsRecycleViewAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.AlbumDetials;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.entity.dao.Collection;
import com.lly.songhigh.entity.dao.CollectionDao;
import com.lly.songhigh.entity.dao.RecentPlay;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.greendao.DaoSingleton;
import com.lly.songhigh.service.DownloadServices;
import com.lly.songhigh.utils.SharedPreferencesUtils;
import com.lly.songhigh.view.PublishSelectPicPopupWindow;
import com.lly.songhigh.volley.VolleySingleton;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by 李海龙 on 15/10/30.
 */
public class SearchAlbumDetialsActivity extends BaseActivity implements View.OnClickListener, AlbumDetialsRecycleViewAdapter.OnItemListener, AlbumDetialsRecycleViewAdapter.OnMenuClickListener {

    private ImageView albumDetialsImg, albumDetialsToorbarBack;
    private CollapsingToolbarLayout albumDetialsCollapsingToolbarLayout;
    private TextView albumDetialsListenCount, albumDetialsDesc, album_detials_singerName;
    private RecyclerView albumRecyclerView;

    private int albumId;
    private String albumUrl;
    private VolleySingleton volleySingleton;

    private AlbumDetials.DataEntity datas;
    private List<AlbumDetials.SongListEntity> songListEntity;
    private AlbumDetials.SongListEntity itemSongEntity;
    private AlbumDetialsRecycleViewAdapter adapter;

    private TextView pw_collection, pw_download, pw_share, pw_singer, pw_album, pw_song_info, album_detials_albumName;
    private RelativeLayout alpha_layout;
    private LinearLayout pop_layout;
    private PublishSelectPicPopupWindow menuWindow;
    private ListView albumDownListView;
    private AlertDialog alertDialog;
    private List<MusicInfo> musicInfos;
    private CollectionDao collectionDao;
    private DaoSingleton daoSingleton;
    private List<Collection> collections;
    private android.support.v7.app.AlertDialog.Builder builder;

    private int downloadCount = 0;
    private String path;

    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private String shareUrl;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_specialalbum_detials);
        BaseApplication.getInstance().addActivity(this);
        initView();
        initData();
        initShare();
    }

    private void initView() {
        alpha_layout = (RelativeLayout) findViewById(R.id.album_detials_alpha_layout);
        albumDetialsImg = (ImageView) findViewById(R.id.album_details_img);
        albumDetialsToorbarBack = (ImageView) findViewById(R.id.album_detias_back);
        albumDetialsCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.album_detials_collapsing_toolbar);
        albumDetialsCollapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.CollapsingToolbarLayoutText);
        albumDetialsListenCount = (TextView) findViewById(R.id.album_details_listen_count);
        albumDetialsDesc = (TextView) findViewById(R.id.album_details_description);
        albumRecyclerView = (RecyclerView) findViewById(R.id.album_detials_recycler_view);
        albumDetialsToorbarBack = (ImageView) findViewById(R.id.album_detias_back);
        album_detials_albumName = (TextView) findViewById(R.id.album_detials_albumName);
        albumDetialsToorbarBack.setOnClickListener(this);
        // 设置列表布局的方向, 通过布局管理器对象
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        albumRecyclerView.setLayoutManager(layoutManager);
        album_detials_singerName = (TextView) findViewById(R.id.album_detials_singerName);
        Intent intent = getIntent();
        albumId = intent.getIntExtra("_url", 1);
        albumUrl = URL.ALBUM_DETIALS_STARTURL + albumId + URL.ALBUM_DETIALS_ENDURL;
        shareUrl = "http://m.dongting.com/?song_id=" + albumId + "&from=uc";

        volleySingleton = VolleySingleton.getInstance();

    }
    private void initData() {
        daoSingleton = DaoSingleton.getInstance();
        musicInfos = new ArrayList<>();
        StringRequest request = new StringRequest(albumUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                AlbumDetials albumDetials = gson.fromJson(response, AlbumDetials.class);
                datas = albumDetials.getData();
                albumDetialsListenCount.setText(datas.getFavoriteCount() + "");
                albumDetialsDesc.setText(datas.getDescription());
                album_detials_singerName.setText(datas.getSingerName());
                albumDetialsCollapsingToolbarLayout.setTitle(datas.getName());
                album_detials_albumName.setText(datas.getName());
                Picasso.with(SearchAlbumDetialsActivity.this).load(datas.getPicUrl()).placeholder(R.mipmap.placeholder_detail_radio_ban)
                        .error(R.mipmap.placeholder_detail_radio_ban).into(albumDetialsImg);
                songListEntity = datas.getSongList();
                if (songListEntity.size() == 0) {
                    Toast.makeText(SearchAlbumDetialsActivity.this, StringResouce.NO_SONGS_INALBUM, Toast.LENGTH_SHORT).show();
                } else {
                    adapter = new AlbumDetialsRecycleViewAdapter(SearchAlbumDetialsActivity.this, songListEntity);
                    albumRecyclerView.setAdapter(adapter);
                    adapter.setOnItemListener(SearchAlbumDetialsActivity.this);
                    adapter.setOnMenuClickListener(SearchAlbumDetialsActivity.this);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.album_detias_back:
                finish();
                break;
        }
    }

    @Override
    public void onItemClick(AlbumDetials.SongListEntity songEntity, int position) {
        if (songEntity.getUrlList() != null && songEntity.getUrlList().size() > 0) {
            Intent intent = new Intent(SearchAlbumDetialsActivity.this, PlayMusicActivity.class);
            daoSingleton.getRecentPlayDao().insertOrReplace(new RecentPlay(songEntity.getName(),
                    songEntity.getSingerName(), songEntity.getAlbumName(),
                    StringResouce.RESOUCE_NET, songEntity.getUrlList().get(0).getUrl(),
                    (long)songEntity.getAlbumId(), (long)songEntity.getUrlList().get(0).getDuration(),
                    (long)songEntity.getSongId()));
            musicInfos = new ArrayList<>();
            for (AlbumDetials.SongListEntity entity : songListEntity) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerId(entity.getSingerId());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setSongId(entity.getSongId());
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setResouce(StringResouce.RESOUCE_NET);
                    musicInfos.add(musicInfo);
                }
            }
            EventBus.getDefault().post(new MyEvent.DeliverData(musicInfos, songEntity.getName()));
            startActivity(intent);
        } else {
            Toast.makeText(SearchAlbumDetialsActivity.this, StringResouce.PLAY_ERROR, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onMenuClick(AlbumDetials.SongListEntity songListEntity) {

        View view = LayoutInflater.from(this).inflate(R.layout.popup_window, null);
        itemSongEntity = songListEntity;
        pw_collection = (TextView) view.findViewById(R.id.pw_collection);
        pw_download = (TextView) view.findViewById(R.id.pw_download);
        pw_share = (TextView) view.findViewById(R.id.pw_share);
        pw_singer = (TextView) view.findViewById(R.id.pw_singer);
        pw_album = (TextView) view.findViewById(R.id.pw_album);
        pop_layout = (LinearLayout) view.findViewById(R.id.pop_layout);
        pw_song_info = (TextView) view.findViewById(R.id.pw_song_info);
        pw_song_info.setText(StringResouce.SONGNAME + songListEntity.getName());
        pw_singer.setText(StringResouce.SINGERNAME + songListEntity.getSingerName());
        if (songListEntity.getAlbumName() != null && !songListEntity.getAlbumName().equals("")) {
            pw_album.setText(StringResouce.ALBUMNAME + songListEntity.getAlbumName());
        }
        menuWindow = new PublishSelectPicPopupWindow(this, itemsOnClick, view, alpha_layout);
        menuWindow.showAtLocation(findViewById(R.id.album_detials_appbar),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        alpha_layout.setVisibility(View.VISIBLE);
        collections = daoSingleton.getCollectionById((int) songListEntity.getSongId());
        if (collections.size() > 0 && collections != null)
            pw_collection.setText(StringResouce.CANCEL_COLLECTION);
        else
            pw_collection.setText(StringResouce.COLLECTION);
    }
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        private AlertDialog.Builder builder;
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            alpha_layout.setVisibility(View.GONE);
            switch (v.getId()) {
                case R.id.pw_collection:
                    if (!(collections.size() > 0 && collections != null)) {
                        Collection collection = new Collection();
                        collection.setSongName(itemSongEntity.getName());
                        collection.setDuration((long) itemSongEntity.getUrlList().get(0).getDuration());
                        collection.setAlbumId((long) itemSongEntity.getAlbumId());
                        collection.setAlbum(itemSongEntity.getAlbumName());
                        collection.setPlayUrl(itemSongEntity.getUrlList().get(0).getUrl());
                        collection.setSingerName(itemSongEntity.getSingerName());
                        collection.setSongId((long) itemSongEntity.getSongId());
                        collection.setResouce(StringResouce.RESOUCE_NET);
                        daoSingleton.getCollectionDao().insert(collection);
                        Toast.makeText(SearchAlbumDetialsActivity.this, StringResouce.COLLECTION_SUCCESS, Toast.LENGTH_LONG).show();
                    } else {
                        daoSingleton.deleteCollectionById(itemSongEntity.getSongId());
                        Toast.makeText(SearchAlbumDetialsActivity.this, StringResouce.DELETE_COLLECTION, Toast.LENGTH_LONG).show();
                    }
                    break;
                case R.id.pw_share:

                    mController.openShare(SearchAlbumDetialsActivity.this, false);
                    QQShare();

                    break;
                case R.id.pw_download:

                    if (itemSongEntity.getAuditionList().size() == 0) {
                        Toast.makeText(SearchAlbumDetialsActivity.this, StringResouce.NO_RESOURCES, Toast.LENGTH_SHORT).show();
                    }else {
                        SharedPreferencesUtils.putSharePre(SearchAlbumDetialsActivity.this,
                                "Download", "SongName", itemSongEntity.getName());
                        View view = LayoutInflater.from(SearchAlbumDetialsActivity.this).inflate(R.layout.downloaddialog, null);
                        albumDownListView = (ListView) view.findViewById(R.id.download_listView);
                        AlbumDetialsDownloadAdapter adapter = new AlbumDetialsDownloadAdapter(itemSongEntity.getAuditionList(), SearchAlbumDetialsActivity.this);
                        albumDownListView.setAdapter(adapter);
                        builder = new AlertDialog.Builder(SearchAlbumDetialsActivity.this);
                        builder.setMessage(StringResouce.CHOOSE_QUALITY);
                        builder.setView(view);
                        alertDialog = builder.create();
                        alertDialog.show();
                        albumDownListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                startDownloadService();
                                path = itemSongEntity.getAuditionList().get(position).getUrl();
                                alertDialog.dismiss();
                                Toast.makeText(SearchAlbumDetialsActivity.this, StringResouce.START_DOWNLOADING, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    break;
                case R.id.pw_singer:
                    Intent intent = new Intent(SearchAlbumDetialsActivity.this, SingerDetailActivity.class);
                    intent.putExtra("singerId", itemSongEntity.getSingerId());
                    startActivity(intent);
                    break;

                case R.id.pw_album:
                    Intent intentToAlbum = new Intent(SearchAlbumDetialsActivity.this, SearchAlbumDetialsActivity.class);
                    intentToAlbum.putExtra("_url", itemSongEntity.getAlbumId());
                    startActivity(intentToAlbum);
                    break;
            }
        }
    };


    public void onEventMainThread(MyEvent.IsDlding isDlding) {
        if (isDlding.isDownloading()) {
            EventBus.getDefault().post(new MyEvent.DldMessage(itemSongEntity.getName(), path));
            downloadCount++;
        }
    }
    public void startDownloadService() {
        Intent i = new Intent(SearchAlbumDetialsActivity.this, DownloadServices.class);
        SearchAlbumDetialsActivity.this.startService(i);
    }


    private void initShare() {
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        umqqSsoHandler.addToSocialSDK();
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }

    private void QQShare() {
        QQShareContent qqShareContent = new QQShareContent();
        //设置分享文字
        qqShareContent.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享title
        qqShareContent.setTitle(StringResouce.SHARE_TITLE);
        //设置点击分享内容的跳转连接
        qqShareContent.setTargetUrl(shareUrl);

        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享内容的标题
        qzone.setTitle(StringResouce.SHARE_TITLE);
        //设置点击消息的跳转URL
        qzone.setTargetUrl(shareUrl);
        mController.setShareMedia(qzone);

        SinaShareContent shareContent =  new SinaShareContent();
        shareContent.setTitle(StringResouce.SHARE_TITLE);
        shareContent.setShareContent(StringResouce.SHARE_CONTENT + shareUrl);
        mController.setShareMedia(shareContent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
